﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Linq;
using MyAlbum.Utility;


namespace MyAlbum.Data.Xml
{
    public abstract class XmlRepository
    {
        private string _fileName;
        protected string _rootPath;
        public string FilePath
        {
            get
            {
                return Path.Combine(this._rootPath, this._fileName);
            }
        }

        private XDocument _document;
        public XDocument Document
        {
            get
            {
                if (this._document == null)
                {
                    this._document = XDocument.Parse(File.ReadAllText(FilePath));

                }
                return this._document;
            }
        }

        public void Save()
        {
            this.Document.Save(this.FilePath);
        }

        public XmlRepository(string rootPath, string fileName)
        {
            if (rootPath == null)
            {
                rootPath = Directory.GetCurrentDirectory();
            }
            this._rootPath = rootPath;
            Assert.IsNotNull(fileName,"fileName");
            if (string.Compare(Path.GetExtension(fileName), ".xml", true) != 0)
            {
                fileName = Path.ChangeExtension(fileName, ".xml");
            }
            this._fileName = fileName;
            if (!File.Exists(FilePath))
            {
                string rootName = Path.GetFileNameWithoutExtension(fileName);
                this._document = new XDocument(
                    new XDeclaration("1.0", "utf-8", "yes"),
                    new XElement(rootName));
                this._document.Save(FilePath);
            }
        }
    }
}
